import React, { useEffect, useState } from 'react';

import { useParams } from 'react-router-dom';

import { ArrowLeftOutlined } from '@ant-design/icons';

import { equipmentProductDetailApi, type ProductDetailItem } from '@/api/equipmentProductApi';
import { getFullAddress } from '@/components/CitySelect/utils';
import ExpandableDescriptions from '@/components/ExpandableCard/ExpandableDescriptions';
import { ProductNodeType } from '@/constants';
import { useRouter } from '@/hooks/useRouter';
import { renderValue } from '@/utils/renderUtils';

import DeviceArchiveTable from './DeviceArchiveTable';
import ModelArchiveTable from './ModelArchiveTable';

/**
 * 产品详情页
 */
const EquipmentProductDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const { back } = useRouter();
  const [loading, setLoading] = useState(true);
  const [productDetail, setProductDetail] = useState<ProductDetailItem | null>(null);
  const [activeTabKey, setActiveTabKey] = useState('deviceList');

  // 获取产品详情
  const fetchProductDetail = async () => {
    if (!id) return;

    try {
      setLoading(true);
      const res = await equipmentProductDetailApi({ id });
      if (res.success) {
        setProductDetail(res.data as ProductDetailItem);
      }
    } catch (error) {
      console.error('获取产品详情失败:', error);
      window.$message.error('获取产品详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 物模型刷新方法（保持当前 tab 状态）
  const handleModelRefresh = async (cb: () => void) => {
    if (!id) return;

    try {
      const res = await equipmentProductDetailApi({ id });
      if (res.success) {
        setProductDetail(res.data as ProductDetailItem);
        // 不改变 loading 状态，不改变 activeTabKey
        if (cb) {
          cb();
        }
      }
    } catch (error) {
      console.error('刷新产品详情失败:', error);
      window.$message.error('刷新产品详情失败');
    }
  };

  useEffect(() => {
    fetchProductDetail();
  }, [id]);

  // 获取节点类型标签
  const getNodeTypeTag = (nodeType: number) => {
    const nodeTypeItem = Object.values(ProductNodeType).find(item => item.value === nodeType);
    return nodeTypeItem ? nodeTypeItem.label : '未知';
  };

  // 处理缩略图显示
  const getThumbnailImages = (thumbnail?: string) => {
    if (!thumbnail) return [];
    try {
      const pData = JSON.parse(thumbnail);
      return pData;
    } catch (error) {
      console.error('解析缩略图失败:', error);
      return [];
    }
  };

  // 处理网络模式显示（预留功能）
  const _getNetworkModes = (networkMode?: string) => {
    if (!networkMode) return [];
    try {
      const modes = JSON.parse(networkMode);
      return Array.isArray(modes) ? modes : [];
    } catch (error) {
      console.warn('解析网络模式失败:', error);
      return [networkMode];
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-96">
        <ASpin size="large" />
      </div>
    );
  }

  if (!productDetail) {
    return (
      <div className="text-center py-8">
        <p>产品详情不存在</p>
        <AButton onClick={() => navigate('/equipment/product')}>返回产品列表</AButton>
      </div>
    );
  }

  return (
    <div className="page-wrapper">
      <div className="page-title">
        <ArrowLeftOutlined className="mx-4" onClick={back} />
        <div className="page-main-title">产品详情</div>
        <div className="page-sub-title">提供产品详情编辑及物模型设置功能</div>
      </div>
      <div className="page-content-box">
        <div className="page-content">
          <ExpandableDescriptions
            title="基本信息"
            className="mb-6"
            defaultExpanded={false}
            basicItems={[
              <ADescriptions.Item key="productName" label="产品名称">
                {renderValue(productDetail.productName)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="code" label="产品code">
                {renderValue(productDetail.code)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="keyInfo" label="产品key">
                {renderValue(productDetail.keyInfo)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="deviceCount" label="设备数量">
                {renderValue(productDetail.deviceCount)}
              </ADescriptions.Item>,
            ]}
            expandedItems={[
              <ADescriptions.Item key="productModel" label="产品型号">
                {renderValue(productDetail.productModel)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="nodeType" label="节点类型">
                <ATag color="blue">{getNodeTypeTag(productDetail.nodeType || 0)}</ATag>
              </ADescriptions.Item>,
              // <ADescriptions.Item key="categoryName" label="产品分类">
              //   {renderValue(productDetail.categoryName)}
              // </ADescriptions.Item>,
              <ADescriptions.Item key="accessProtocolName" label="接入协议">
                {renderValue(productDetail.accessProtocolName)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="manufacturer" label="厂商名称">
                {renderValue(productDetail.manufacturer)}
              </ADescriptions.Item>,
              // <ADescriptions.Item key="networkMode" label="联网方式">
              //   {getNetworkModes(productDetail.networkMode).length > 0 ? (
              //     <ASpace wrap>
              //       {getNetworkModes(productDetail.networkMode).map((mode, index) => (
              //         <ATag key={index} color="blue">
              //           {mode}
              //         </ATag>
              //       ))}
              //     </ASpace>
              //   ) : (
              //     renderValue(null, '暂无数据')
              //   )}
              // </ADescriptions.Item>,
              <ADescriptions.Item key="address" label="所属地区">
                {renderValue(
                  getFullAddress({
                    province: productDetail.provinceName,
                    city: productDetail.cityName,
                  })
                )}
              </ADescriptions.Item>,
              <ADescriptions.Item key="remark" label="创建时间">
                {renderValue(productDetail.createTime)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="remark" label="产品描述" span={2}>
                {renderValue(productDetail.remark)}
              </ADescriptions.Item>,
              <ADescriptions.Item key="thumbnail" label="产品图片" span={2}>
                {productDetail.thumbnail ? (
                  <ASpace wrap>
                    {getThumbnailImages(productDetail.thumbnail).map((url, index) => (
                      <AImage
                        key={index}
                        width={120}
                        height={90}
                        src={url}
                        alt={`产品图片 ${index + 1}`}
                        style={{
                          objectFit: 'cover',
                          borderRadius: '6px',
                          border: '1px solid #f0f0f0',
                        }}
                        fallback=""
                      />
                    ))}
                  </ASpace>
                ) : (
                  <span className="color-#999 text-3.5">暂无图片</span>
                )}
              </ADescriptions.Item>,
            ]}
          />

          {/* 设备管理卡片 */}
          <ACard className="mt-6">
            <ATabs
              activeKey={activeTabKey}
              onChange={setActiveTabKey}
              items={[
                {
                  key: 'deviceList',
                  label: '设备档案',
                  children: <DeviceArchiveTable activeItem={productDetail} />,
                },
                {
                  key: 'thingModel',
                  label: '物模型管理',
                  children: (
                    <ModelArchiveTable onRefresh={handleModelRefresh} activeItem={productDetail} />
                  ),
                },
              ]}
            />
          </ACard>
        </div>
      </div>
    </div>
  );
};

export default EquipmentProductDetail;
